package com.zeros.myself.utils.network;

//import com.yunbao.financial.HujinApplication;
//import com.yunbao.financial.common.Setting;
//import com.yunbao.financial.model.ApiItem;
//import com.yunbao.financial.model.OssInfo;
//import com.yunbao.financial.model.Version;
//import com.yunbao.financial.utils.tip.ZLog;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Dispatcher;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
//import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

//import static com.yunbao.financial.common.Config.serverFlag;

/**
 * Retrofit
 */

public class APIService {

    private static final int DEFAULT_TIMEOUT = 5;
    private APIs apis;
    private Dispatcher dispatcher;
    private Retrofit retrofit;          //retrofit网络请求库,对OKhttp的封装
    private OkHttpClient client;

//    private APIs apis2;
//    private Retrofit retrofit2;          //retrofit网络请求库,对OKhttp的封装
//    private Retrofit.Builder builder;

    private static String getBaseUrl() {
        String str = "";
//        switch (serverFlag) {
//            case 0:
//                str = "http://192.168.31.101:8085";
//                break;
//            case 1:
//                str = Setting.ROOT_URL;
//                break;
//            default:
//                break;
//        }
        return str;
    }

    //构造方法--创建客户端
    private APIService() {
        dispatcher = new Dispatcher(Executors.newFixedThreadPool(20));//指定可以运行的线程的最大数目
        dispatcher.setMaxRequests(20);              //最大的请求数量
        dispatcher.setMaxRequestsPerHost(1);        //主机同一个时间，最大的请求数量

        //只是查看网络返回的信息
//        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
//        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //设置UA
        String agent = System.getProperty("http.agent");
        if (agent == null)
            agent = ("Java" + System.getProperty("java.version"));

        //添加token访问--header
        final String finalAgent = agent;
        Interceptor mTokenInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder()
                        .removeHeader("User-Agent")
                        .addHeader("User-Agent", finalAgent)
//                        .header("token", HujinApplication.getToken().getTokenCode())
                        .build();
//                ZLog.e(request.header("User-Agent"));

                return chain.proceed(request);
            }
        };


        client = new OkHttpClient.Builder()
                .dispatcher(dispatcher)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)  //设定15秒超时
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
//                .addInterceptor(interceptor)
                .addNetworkInterceptor(mTokenInterceptor)
                .build();

        retrofit = new Retrofit.Builder()
                .client(client)                 //构建RetrofitClient客户端
                .addConverterFactory(GsonConverterFactory.create())     //添加一个Gson转换器工厂。
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())//配置回调库，采用RxJava，增加返回值为Oservable<T>的支持
                .baseUrl(getBaseUrl())          //配置服务器路径
                .build();

//        builder = new Retrofit.Builder()
//                .client(client)                 //构建RetrofitClient客户端
//                .addConverterFactory(GsonConverterFactory.create())     //添加一个Gson转换器工厂。
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync());//配置回调库，采用RxJava，增加返回值为Oservable<T>的支持

        apis = retrofit.create(APIs.class);

    }

    //单例
    private static class SingletonHolder {
        private static final APIService INSTANCE = new APIService();
    }

    public static APIService getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /************-------创建实例 End -----------***********************/

    //设置观察者 与 被观察者
    private <T> void toSubscribe(Observable<T> observable, Observer<T> observer) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    //Function的泛型第一个为接收参数的数据类型，第二个为转换后要发射的数据类型
    //在2.x中将1.x的Func1和Func2改为Function和BiFunction，Func3-9改为Function3-9，多参数FuncN改为Function<Object[],R>
    private class resultFunc implements Function<Object, Object> {
        @Override
        public Object apply(Object o) throws Exception {
//            ZLog.e( String.valueOf(o));
            return o;
        }
    }


    /********-----以下是访问网络接口方法----**********/
    //一般用于JS交互中
//    public void uncertainAPI(ApiItem item, Observer<Object> observer) {
//
////        String url = item.getUrl();
////        HashMap<String, String> params = item.getBody();
////
////        ZLog.e("Tag-"+url.toString());
//
//        //http://192.168.31.57:8080//user/activity/find?page=1&pageSize=3
////        String url2 = url.substring(0, 26);// http://192.168.31.57:8080/
////        String url2 = url.substring(0, url.lastIndexOf("/") + 1);
////        String url3 = url.substring(url.lastIndexOf("/") + 1);
////        Log.e("Tag-", url2.toString());
////        params.put("UncertainURL", url3);
////        Log.e("Tag-----------",params.toString());
//
////        retrofit2 = builder.baseUrl(url2)
////                .build();
////        apis2 = retrofit2.create(APIs.class);
//
////        Observable observable = apis2.uncertainAPI(url3, params)
////                .map(new resultFunc());
////        toSubscribe(observable, observer);
//
//        Observable observable1 = apis.uncertainAPI2(url, params)
//                .map(new resultFunc());
//        toSubscribe(observable1, observer);
//    }


    /**
     * 2. 更新版本get_domain
     */
    public void test(Observer<Object> observer) {
        Observable observable = apis.testDo_main()
                .map(new resultFunc());
        toSubscribe(observable, observer);
    }

    /**
     * 3. 获取token
     */
    public void requestToken(Observer<String> observer) {
        Observable observable = apis.requestToken()
                .map(new resultFunc());
        toSubscribe(observable, observer);
    }

    public void myInvest(Observer<String> observer) {
        Observable observable = apis.myInvest()
                .map(new resultFunc());
        toSubscribe(observable, observer);
    }


    /**
     * 4. 获取Oss参数
     * @param url Oss地址
     */
//    public void getOssInfo(String url, Observer<OssInfo> observer){
//        Observable observable = apis.getOssInfo(url)
//                .map(new resultFunc());
//        toSubscribe(observable, observer);
//    }



    /**
     * 2.1 更新版本get_domain
     */
//    public void doMain(Observer<Version> observer) {
//        Observable observable = apis.doMain()
//                .map(new resultFunc());
//        toSubscribe(observable, observer);
//    }


}


